<!DOCTYPE html>
<html>
<head>
    <title>Canvas图片裁切成正方形</title>
</head>
<body>
    <input type="file" id="fileInput" accept="image/*">
    <canvas id="canvas" width="300" height="300"></canvas>
    <img id="output" style="display: none;">
    
    <script>
        const fileInput = document.getElementById('fileInput');
        const canvas = document.getElementById('canvas');
        const ctx = canvas.getContext('2d');
        const output = document.getElementById('output');
        
        fileInput.addEventListener('change', function (event) {
            const file = event.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function (e) {
                    const img = new Image();
                    img.src = e.target.result;
                    img.onload = function () {
                        const size = Math.min(img.width, img.height);
                        canvas.width = size;
                        canvas.height = size;
                        
                        // 计算裁切的位置，使图片居中
                        const x = (img.width - size) / 2;
                        const y = (img.height - size) / 2;
                        
                        // 在Canvas上绘制裁切后的图像
                        ctx.drawImage(img, x, y, size, size, 0, 0, size, size);
                        
                        // 将Canvas上的图像数据转为DataURL
                        const squareImageDataURL = canvas.toDataURL('image/jpeg');
                        
                        // 显示裁切后的图像
                        output.src = squareImageDataURL;
                        output.style.display = 'block';
                    };
                };
                reader.readAsDataURL(file);
            }
        });
    </script>
</body>
</html>
